package main

import (
	"io/ioutil"
	"log"
	"net/http"
	"os/exec"
	"regexp"
	"runtime"
	"strconv"
	"strings"
	"time"
)

func getNetTime() int64 {
	url := "http://open.baidu.com/special/time/"
	resp, err := http.Get(url)
	dealErr(err)
	respHtml, err := ioutil.ReadAll(resp.Body)
	dealErr(err)
	defer resp.Body.Close()
	if err != nil {
		log.Fatal(err)
	}
	timePattern, err := regexp.Compile(`baidu_time\((\d+)\)`)
	dealErr(err)
	matchers := timePattern.FindAllStringSubmatch(string(respHtml), -1)
	ret, err := strconv.ParseInt(matchers[0][1], 10, 64)
	dealErr(err)
	return ret
}

func dealErr(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

func getTime(milTime int64) time.Time {
	seconds := int64(milTime / 1000)
	log.Printf("seconds :%d\n", seconds)
	return time.Unix(seconds, 0)
}

func main() {
	timeStamp := getNetTime()
	log.Printf("baiduTime %d\n", timeStamp)
	t := getTime(timeStamp)
	log.Printf("netTime:%s\n", t.Format("2006-01-02 15:04:05"))

	os := runtime.GOOS
	log.Printf("system os : %s", os)
	if strings.Contains(os, "windows") {
		windowsSetTime(t)
	} else {
		linuxSetTime(t)
	}

}

func windowsSetTime(t time.Time) {
	var err error
	var cmd *exec.Cmd
	cmd = exec.Command("cmd", "/c", "date", t.Format("2006-01-02"))
	err = cmd.Run()
	if err != nil {
		log.Fatal(err)
	}
	cmd = exec.Command("cmd", "/c", "time", t.Format("15:04:05"))
	err = cmd.Run()
	if err != nil {
		log.Fatal(err)
	}
}

func linuxSetTime(t time.Time) {
	var err error
	var cmd *exec.Cmd
	cmd = exec.Command("date", "-s", t.Format("15:04:05 2006-01-02"))
	err = cmd.Run()
	if err != nil {
		log.Fatal(err)
	}
}
